using System;
using System.Drawing;
using System.Windows.Forms;

namespace LTKJ.RTU
{
    /// <summary>
    /// 性能监控面板 - 实时显示系统性能状态
    /// </summary>
    public partial class PerformancePanel : UserControl
    {
        private readonly Timer updateTimer;
        private readonly DataCacheManager cacheManager;
        private readonly AsyncTaskManager taskManager;
        
        private Label lblCacheStatus;
        private Label lblTaskStatus;
        private Label lblMemoryUsage;
        private Label lblThreadCount;
        private ProgressBar pbCacheUsage;
        private ProgressBar pbTaskUsage;
        
        public PerformancePanel(DataCacheManager cacheMgr, AsyncTaskManager taskMgr)
        {
            cacheManager = cacheMgr;
            taskManager = taskMgr;
            
            InitializeComponent();
            
            // 启动定时更新
            updateTimer = new Timer();
            updateTimer.Interval = 2000; // 2秒更新一次
            updateTimer.Tick += UpdateTimer_Tick;
            updateTimer.Start();
        }
        
        private void InitializeComponent()
        {
            this.Size = new Size(300, 200);
            this.BackColor = Color.LightGray;
            this.BorderStyle = BorderStyle.FixedSingle;
            
            // 缓存状态标签
            lblCacheStatus = new Label
            {
                Text = "缓存状态: 初始化中...",
                Location = new Point(10, 10),
                Size = new Size(280, 20),
                Font = new Font("Microsoft YaHei", 9)
            };
            
            // 缓存使用率进度条
            pbCacheUsage = new ProgressBar
            {
                Location = new Point(10, 35),
                Size = new Size(280, 20),
                Maximum = 100
            };
            
            // 任务状态标签
            lblTaskStatus = new Label
            {
                Text = "任务状态: 初始化中...",
                Location = new Point(10, 65),
                Size = new Size(280, 20),
                Font = new Font("Microsoft YaHei", 9)
            };
            
            // 任务使用率进度条
            pbTaskUsage = new ProgressBar
            {
                Location = new Point(10, 90),
                Size = new Size(280, 20),
                Maximum = 100
            };
            
            // 内存使用标签
            lblMemoryUsage = new Label
            {
                Text = "内存使用: 0 MB",
                Location = new Point(10, 120),
                Size = new Size(140, 20),
                Font = new Font("Microsoft YaHei", 9)
            };
            
            // 线程数量标签
            lblThreadCount = new Label
            {
                Text = "活动线程: 0",
                Location = new Point(160, 120),
                Size = new Size(130, 20),
                Font = new Font("Microsoft YaHei", 9)
            };
            
            // 添加控件
            this.Controls.AddRange(new Control[]
            {
                lblCacheStatus,
                pbCacheUsage,
                lblTaskStatus,
                pbTaskUsage,
                lblMemoryUsage,
                lblThreadCount
            });
        }
        
        private void UpdateTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                UpdatePerformanceInfo();
            }
            catch (Exception ex)
            {
                // 静默处理异常，避免影响主程序
                System.Diagnostics.Debug.WriteLine($"性能面板更新异常: {ex.Message}");
            }
        }
        
        private void UpdatePerformanceInfo()
        {
            if (cacheManager != null)
            {
                var cacheStats = cacheManager.GetCacheStatistics();
                lblCacheStatus.Text = $"缓存状态: {cacheStats.TotalCachedItems} 项, {cacheStats.PendingUpdates} 待更新";
                
                // 计算缓存使用率
                int cacheUsagePercent = (int)((double)cacheStats.TotalCachedItems / 1000 * 100);
                pbCacheUsage.Value = Math.Min(cacheUsagePercent, 100);
                
                // 根据使用率设置颜色
                if (cacheUsagePercent > 80)
                {
                    pbCacheUsage.ForeColor = Color.Red;
                }
                else if (cacheUsagePercent > 60)
                {
                    pbCacheUsage.ForeColor = Color.Orange;
                }
                else
                {
                    pbCacheUsage.ForeColor = Color.Green;
                }
            }
            
            if (taskManager != null)
            {
                var taskStats = taskManager.GetTaskStatistics();
                lblTaskStatus.Text = $"任务状态: {taskStats.ActiveTasks} 活动, {taskStats.QueuedTasks} 排队";
                
                // 计算任务使用率
                int taskUsagePercent = (int)((double)taskStats.ActiveTasks / taskStats.MaxConcurrentTasks * 100);
                pbTaskUsage.Value = Math.Min(taskUsagePercent, 100);
                
                // 根据使用率设置颜色
                if (taskUsagePercent > 80)
                {
                    pbTaskUsage.ForeColor = Color.Red;
                }
                else if (taskUsagePercent > 60)
                {
                    pbTaskUsage.ForeColor = Color.Orange;
                }
                else
                {
                    pbTaskUsage.ForeColor = Color.Green;
                }
            }
            
            // 更新系统信息
            try
            {
                var process = System.Diagnostics.Process.GetCurrentProcess();
                process.Refresh();
                
                long memoryMB = process.WorkingSet64 / (1024 * 1024);
                lblMemoryUsage.Text = $"内存使用: {memoryMB} MB";
                
                lblThreadCount.Text = $"活动线程: {process.Threads.Count}";
            }
            catch
            {
                lblMemoryUsage.Text = "内存使用: 未知";
                lblThreadCount.Text = "活动线程: 未知";
            }
        }
        
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                updateTimer?.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
